﻿using dz.loger.core;
using dz.u9.jky.schema.Common;
using dz.u9.jky.schema.SM;
using dz.util.core;
using Dz.WorkerService.Utils;
using System.Data;

namespace Dz.WorkerService.Service
{
    /// <summary>
    /// 线上退回处理
    /// </summary>
    public class RmaOnLineService : RmaBaseService
    {
        public RmaOnLineService(string processId) : base(processId)
        {
            docType = "退回处理-线上订单";
        }

        protected async override Task<DataTable> GetProcessData()
        {
            string sql = "select distinct org,deptcode,shipdate,wh from dz_jky_SO where flag=2 and sellcount <0 and xtype=1";

            DataTable dt = await sqlUtils.Fill(sql);

            return dt;
        }
        protected override async Task Process()
        {
            foreach (DataRow dr in dt.Rows)
            {
                await Import(dr);
            }

        }

        private async Task Import(DataRow dr)
        {
            string sql = $@"select goodsno,abs(sum(sellcount)) as sellcount,abs(sum(sellamt)) as sellamt from dz_jky_SO 
                        where flag=2 and xtype=1 and sellcount < 0 and org = '{dr["org"]}' and wh = '{dr["wh"]}' 
                        and deptcode = '{dr["deptcode"]}' and shipdate = '{dr["shipdate"]}' 
                        group by goodsno ";

            DataTable result = await sqlUtils.Fill(sql);

            await Import(dr, result);
        }

        private async Task Import(DataRow dr, DataTable dt)
        {
            string org = dr["org"].ToString();
            string wh = dr["wh"].ToString();
            string dept = dr["deptcode"].ToString();

            string cust = DeptUtils.Instance.GetCust(dept, org);

            if (cust == string.Empty)
            {
                LogUtil.Instance.Error($"生成退回处理-线上订单时，通过部门{dept}，组织{org}获得客户失败。");
                return;
            }

            string extWhere = $" and org = '{org}' and wh = '{wh}' and deptcode = '{dept}' and shipdate = '{dr["shipdate"]}'";

            DzRMA rma = new DzRMA();

            rma.DocumentType = documentType;
            rma.Customer = cust;
            rma.Org = org;
            rma.TC = currencys[rma.Org];
            rma.AC = rma.TC;
            rma.BusinessDate = Convert.ToDateTime(dr["shipdate"]);
            rma.Org = org;
            rma.SaleDept = dept;
            string taxSchedule = TaxScheduleUtils.Instance.GetTaxSchedule(dept, org);
            


            List<DzRMALine> lines = new List<DzRMALine>();
            foreach (DataRow row in dt.Rows)
            {
                DzRMALine line = new DzRMALine();

                string inv = row["goodsno"].ToString();

                if (!InvUtils.Instance.IsExists(inv, org))
                {
                    LogUtil.Instance.Debug($"存货{inv} 在U9中不存在，跳过");
                    continue;
                }
          
                line.ItemInfo = inv;
                line.ApplyQtyTU1 =  Math.Abs(Convert.ToDecimal(row["sellcount"]));
                line.RtnQtyTU1 = line.ApplyQtyTU1;
                line.Warehouse = WarehouseUtils.Instance.GetRtnWh(org);
                if (taxSchedule.Length > 0) line.TaxSchedule = taxSchedule;

                decimal amt = Math.Abs(Convert.ToDecimal(row["sellamt"]));
                decimal qty = Math.Abs(Convert.ToDecimal(row["sellcount"]));
                decimal price = Math.Round(amt / qty,6);
                line.OrderPrice = price;
                line.ApplyPrice = price;
                line.RtnMoneyTC = amt;
                

                lines.Add(line);
            }

            if (lines.Count == 0)
            {
                await UpdateDataState(2, extWhere);
                return;
            }

            rma.RMALines = lines;

            //U9CResult result = await U9Utils.Post(controller, "AddAndAudit", JsonUtil.Serialize(ship));

            U9CResult result = await U9Utils.Post(controller, "Add", JsonUtil.Serialize(rma));

            await UpdateSyncLog(result, extWhere);

        }
    }
}
